package com.qf.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.config.RabbitMQConfig;
import com.qf.constant.RabbitMQConstants;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainManager;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * 接收 接口模块发送来的消息
 * @author lixu
 */
@Component
public class InterfaceRabbitListener {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private FilterChainManager filterChainManager;

    /**
     * 监听
     *     // 发送短信的消息交接机 ---  接口模块发送消息到策略模块
     *     public final static String TOPIC_PRE_SEND_EXCHANGE = "pre_send_sms_topic_exchange";
     *     // 发送短信的消息队列名  ---  接口模块发送消息到策略模块
     *     public final static String TOPIC_PRE_SEND = "pre_send_sms_topic";
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = RabbitMQConstants.TOPIC_PRE_SEND_EXCHANGE,type = "topic"),
            value = @Queue(value = RabbitMQConstants.TOPIC_PRE_SEND,durable = "true",autoDelete = "false"),
            key = {RabbitMQConstants.BINDING}// sms
    ))
    public void receiverStandardSubmit(StandardSubmit standardSubmit, Channel channel, Message message){
        try {
            System.out.println(objectMapper.writeValueAsString(standardSubmit));
            //调用责任链管理者 完成 策略微服务中所有策略
            filterChainManager.executeFilter(standardSubmit);
            //正常的确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());

        }
    }

    /**
     * 测试插件的延迟消息
     */
    @RabbitListener(queues = RabbitMQConfig.QUEUE_DELAYED)
    public void receiverDelayMessage(Message message,Channel channel,String msg) throws Exception{

        System.out.println("消息:" + msg + "：接收的时间:" + new Date());


        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
    /**
     * 测试死信的延迟消息
     */
    @RabbitListener(queues = RabbitMQConfig.QUEUE_NORMAL)
    public void receiverDeadLetterMessage(Message message,Channel channel,String msg) throws Exception{
        System.out.println("<死信>消息:" + msg + "：接收的时间:" + new Date());
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


}
